const superagent = require('superagent');
const geohash = require('ngeohash');
const gps2Ue4 = require('./function/GPSToUe4');
// const { geojsonData, formatGaodeParam, Ue4Data, hashData, centerData, ue4centerData } = require('./function/mockGps');
const { geojsonData, formatGaodeParam, Ue4Data } = require('./function/mockGps');
const { GAODE_KEY, JDBC, PRECISION } = require('./config');


const { getDetailAddress, getJurisdiction } = require('./function/common');


// const { START_INDEX, TABLE_NAME, TABLE_KEYS, TABLE_VALUES } = require('./dbscript/actual_population_geo');
// const { START_INDEX, TABLE_NAME, TABLE_KEYS, TABLE_VALUES } = require('./dbscript/actual_building_geo');
const { START_INDEX, TABLE_NAME, TABLE_KEYS, TABLE_VALUES } = require('./dbscript/actual_company_geo');
// const { START_INDEX, TABLE_NAME, TABLE_KEYS, TABLE_VALUES } = require('./dbscript/major_member_geo');
// const { START_INDEX, TABLE_NAME, TABLE_KEYS, TABLE_VALUES } = require('./dbscript/situation_geo');




//格式化数据
let formatResult = addCenterCoordinate(geojsonData);

//添加中心点坐标
function addCenterCoordinate(data){
    //生成对应hash值
    let hashMapList = data.map((item,index) => {
        let [x,y] = item;
        return {
            'index': index,
            'x': x,
            'y': y,
            'hash': geohash.encode(y, x, PRECISION)
        }
    })
    //根据hash分组
    let map = {};
    for(let i = 0;i < hashMapList.length;i++) {
        let hashKey = hashMapList[i].hash;
        if (!map[hashKey]) {
            map[hashKey] = [];
        } else {
            // console.log('cunzai')
        }
        map[hashKey].push(hashMapList[i]);
    }
    //根据同一组计算
    let result = [];
    for (const key in map) {
        // console.log(key, 'key----')
        let valueList = map[key];
        // [
        //     // {x: '',y: '', hash: '', index: ''}
        // ]
        let xList = valueList.map(item => item.x);
        let yList = valueList.map(item => item.y);
        // console.log(xList, '------xList')
        // console.log(yList, '------yList')
        let maxlon = Math.max(...xList);
        let minlon = Math.min(...xList);
        let maxlat = Math.max(...yList);
        let minlat = Math.min(...yList);

        //中心点坐标
        let centerGpsX = (maxlon + minlon) / 2;
        let centerGpsY = (maxlat + minlat) / 2;
        //转化UE4坐标
        // let ue4center = gps2Ue4([centerGpsX,centerGpsY]);

        // console.log([centerGpsX, centerGpsY]);
        // console.log(ue4center)
      
        result = result.concat(valueList.map(item => {
            return {
                'index': item.index,
                'x': item.x,
                'y': item.y,
                'hash': item.hash,
                'center': [centerGpsX, centerGpsY],
                'ue4Center':  gps2Ue4([centerGpsX,centerGpsY])
            }
        }));

    }
    // console.log(result, 'xxxx')
    // 按索引排序
    return result.sort((a, b) => a.index - b.index);
}




start();
async function start(){
    console.log('开始运行...');
    let superagentResult = [];
    console.log('正在请求数据中...');
    for(let i=0;i<formatGaodeParam.length;i++) {
        console.log(`正在进行第${i+1}次请求...`);
        let result = await superagent.get(`https://restapi.amap.com/v3/geocode/regeo?output=json&location=${formatGaodeParam[i]}&key=${GAODE_KEY}&radius=1000&extensions=all&batch=true`).catch((e) => { console.log('获取信息', e); });
        if (!result || !result.text) console.log(`第${i}条高德res为空`);
        let {info, regeocodes:data} = JSON.parse(result.text);
        if (info !== 'OK') {
            console.log('请求数据失败...');
            return;
        }
        superagentResult = superagentResult.concat(data);
    }
    console.log(`请求完成，开始拼装数据...`);
    // console.log(superagentResult, 'superagentResult---')
    let sqlObj = superagentResult.map((item, index) => {
        return {
            'INDEX_id': index + START_INDEX, //索引开始
            'adcode': item.addressComponent.adcode,
            'province': item.addressComponent.province,
            'city': item.addressComponent.city,
            'district': item.addressComponent.district,
            'town_ship': item.addressComponent.township,
            'jurisdiction': getJurisdiction(item.addressComponent.township),
            'detail_address': getDetailAddress(item.formatted_address, item.addressComponent.province, item.addressComponent.city, item.addressComponent.district, item.addressComponent.township),
            // 'lng_x': geojsonData[index][0],
            // 'lat_y': geojsonData[index][1],
            // 'geo_hash': hashData[index],
            'lng_x': formatResult[index]['x'],
            'lat_y': formatResult[index]['y'],
            'geo_hash': formatResult[index]['hash'],
            'internal_coordinate_x': Ue4Data[index][0],
            'internal_coordinate_y': Ue4Data[index][1],
            // 'center_x': centerData[index][0],
            // 'center_y': centerData[index][1],
            // 'internal_coordinate_center_x': ue4centerData[index][0],
            // 'internal_coordinate_center_y': ue4centerData[index][1],
            'center_x': formatResult[index]['center'][0],
            'center_y': formatResult[index]['center'][1],
            'internal_coordinate_center_x': formatResult[index]['ue4Center'][0],
            'internal_coordinate_center_y': formatResult[index]['ue4Center'][1],
            'format_address': item.formatted_address
        }
    })
    console.log(`拼装数据完成，准备连接数据库写入数据...`);

    console.log(sqlObj, 'sqlObj-------')

    //数据库配置
    let pg = require('pg');
    
    let client = new pg.Client(JDBC);
    client.connect(async function(err, client, done){
        if (err) {
            console.log('连接postgresql出错');
        } else {
            console.log('连接postgresql成功');
        
            for(let i=0;i<sqlObj.length;i++) {
                let {
                    INDEX_id, 
                    adcode, 
                    province, 
                    city, 
                    district, 
                    town_ship, 
                    jurisdiction, 
                    detail_address, 
                    lng_x,
                    lat_y,
                    geo_hash,
                    center_x,
                    center_y,
                    internal_coordinate_x,
                    internal_coordinate_y,
                    internal_coordinate_center_x,
                    internal_coordinate_center_y,
                    format_address
                } = sqlObj[i];

                await client.query(`insert into ${TABLE_NAME} (${TABLE_KEYS}) values ( ${TABLE_VALUES})`, [ 
                        INDEX_id, 
                        adcode, 
                        province, 
                        city, 
                        district, 
                        town_ship, 
                        jurisdiction, 
                        detail_address, 
                        lng_x,
                        lat_y,
                        geo_hash,
                        center_x,
                        center_y,
                        internal_coordinate_x,
                        internal_coordinate_y,
                        internal_coordinate_center_x,
                        internal_coordinate_center_y,
                        format_address]
                );
                console.log(`插入第${i+1}条数据成功！`)
            }

        }

        console.log('完成！')
    });
}

